import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/foundation.dart';
import '../models/song.dart';
import '../models/music_source.dart';
import 'music_api_service.dart';
import 'history_service.dart';
import 'audio_quality_service.dart';

enum PlayMode {
  sequence,    // 顺序播放
  loop,        // 列表循环
  single,      // 单曲循环
  shuffle,     // 随机播放
}

enum MusicPlayerState {
  stopped,
  playing,
  paused,
  loading,
  error,
}

class MusicPlayerService extends ChangeNotifier {
  final AudioPlayer _audioPlayer = AudioPlayer();
  final MusicApiService _apiService = MusicApiService();
  final AudioQualityService _qualityService = AudioQualityService();
  
  // 播放状态
  MusicPlayerState _playerState = MusicPlayerState.stopped;
  PlayMode _playMode = PlayMode.sequence;
  
  // 播放列表
  List<Song> _playlist = [];
  int _currentIndex = -1;
  Song? _currentSong;
  
  // 播放进度
  Duration _duration = Duration.zero;
  Duration _position = Duration.zero;
  
  // 音量
  double _volume = 0.4;
  
  // 流订阅
  StreamSubscription? _positionSubscription;
  StreamSubscription? _durationSubscription;
  StreamSubscription? _playerStateSubscription;
  
  // 防抖机制
  Timer? _seekDebounceTimer;
  Duration? _pendingSeekPosition;
  bool _isSeeking = false;
  
  // 错误处理
  String? _lastError;
  int _seekErrorCount = 0;
  static const int _maxSeekErrors = 3;

  // Getters
  MusicPlayerState get playerState => _playerState;
  PlayMode get playMode => _playMode;
  List<Song> get playlist => List.unmodifiable(_playlist);
  int get currentIndex => _currentIndex;
  Song? get currentSong => _currentSong;
  Duration get duration => _duration;
  Duration get position => _position;
  double get volume => _volume;
  bool get isPlaying => _playerState == MusicPlayerState.playing;
  bool get isPaused => _playerState == MusicPlayerState.paused;
  bool get isLoading => _playerState == MusicPlayerState.loading;
  bool get hasNext => _currentIndex < _playlist.length - 1;
  bool get hasPrevious => _currentIndex > 0;
  double get progress => _duration.inMilliseconds > 0 
      ? _position.inMilliseconds / _duration.inMilliseconds 
      : 0.0;
  String? get lastError => _lastError;
  bool get isSeeking => _isSeeking;

  MusicPlayerService() {
    _initializePlayer();
    _loadSavedVolume();
  }

  void _initializePlayer() {
    _audioPlayer.setAudioContext(AudioContext(
      iOS: AudioContextIOS(
        category: AVAudioSessionCategory.playback,
      ),
      android: AudioContextAndroid(
        isSpeakerphoneOn: false,
        stayAwake: true,
        contentType: AndroidContentType.music,
        usageType: AndroidUsageType.media,
        audioFocus: AndroidAudioFocus.gain,
      ),
    ));
    // 设置初始音量
    _audioPlayer.setVolume(_volume);
    
    // 监听播放位置
    _positionSubscription = _audioPlayer.onPositionChanged.listen((position) {
      _position = position;
      notifyListeners();
    });

    // 监听播放时长
    _durationSubscription = _audioPlayer.onDurationChanged.listen((duration) {
      _duration = duration;
      notifyListeners();
    });

    // 监听播放状态
    _playerStateSubscription = _audioPlayer.onPlayerStateChanged.listen((state) {
      switch (state) {
        case PlayerState.playing:
          _playerState = MusicPlayerState.playing;
          break;
        case PlayerState.paused:
          _playerState = MusicPlayerState.paused;
          break;
        case PlayerState.stopped:
          _playerState = MusicPlayerState.stopped;
          break;
        case PlayerState.completed:
          _onSongCompleted();
          break;
        case PlayerState.disposed:
          _playerState = MusicPlayerState.stopped;
          break;
      }
      notifyListeners();
    });
  }

  /// 加载已保存的初始音量设置
  Future<void> _loadSavedVolume() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final saved = prefs.getDouble('initial_volume');
      if (saved != null) {
        _volume = saved.clamp(0.0, 1.0);
        await _audioPlayer.setVolume(_volume);
        notifyListeners();
      }
    } catch (_) {
      // 读取失败忽略，保留默认音量
    }
  }

  /// 设置播放列表
  Future<void> setPlaylist(List<Song> songs, {int startIndex = 0}) async {
    _playlist = List.from(songs);
    _currentIndex = startIndex.clamp(0, _playlist.length - 1);
    notifyListeners();
    
    if (_playlist.isNotEmpty) {
      await playAtIndex(_currentIndex);
    }
  }

  /// 添加歌曲到播放列表
  void addToPlaylist(Song song) {
    _playlist.add(song);
    notifyListeners();
  }

  /// 从播放列表移除歌曲
  void removeFromPlaylist(int index) {
    if (index >= 0 && index < _playlist.length) {
      _playlist.removeAt(index);
      
      if (index == _currentIndex) {
        // 如果移除的是当前播放的歌曲
        if (_playlist.isEmpty) {
          stop();
        } else {
          // 调整当前索引
          if (_currentIndex >= _playlist.length) {
            _currentIndex = _playlist.length - 1;
          }
          playAtIndex(_currentIndex);
        }
      } else if (index < _currentIndex) {
        // 如果移除的歌曲在当前歌曲之前，调整索引
        _currentIndex--;
      }
      
      notifyListeners();
    }
  }

  /// 播放指定索引的歌曲
  Future<void> playAtIndex(int index) async {
    if (index < 0 || index >= _playlist.length) return;
    
    // 立即停止当前播放的歌曲
    await _audioPlayer.stop();
    
    _currentIndex = index;
    _currentSong = _playlist[index];
    _playerState = MusicPlayerState.loading;
    notifyListeners();

    try {
      // 如果已有本地缓存路径，直接离线播放
      if (_currentSong?.audioUrl != null && _currentSong!.audioUrl!.isNotEmpty &&
          !_currentSong!.audioUrl!.toLowerCase().startsWith('http')) {
        await _audioPlayer.play(DeviceFileSource(_currentSong!.audioUrl!));
        _playerState = MusicPlayerState.playing;
        HistoryService.addToHistory(_currentSong!);
        notifyListeners();
        return;
      }

      // 获取完整的歌曲信息（包括播放URL），使用当前选择的音质
      final completeSong = await _apiService.getCompleteSongInfo(
        _currentSong!, 
        quality: _qualityService.selectedQuality,
      );
      _currentSong = completeSong;
      _playlist[index] = completeSong;

      if (completeSong.audioUrl != null && completeSong.audioUrl!.isNotEmpty) {
        await _audioPlayer.play(UrlSource(completeSong.audioUrl!));
        _playerState = MusicPlayerState.playing;
        
        // 添加到播放历史
        HistoryService.addToHistory(completeSong);
      } else {
        _playerState = MusicPlayerState.error;
        print('无法获取歌曲播放链接: ${_currentSong!.name} - ${_currentSong!.artistsString}');
        throw Exception('无法获取歌曲播放链接，请尝试其他歌曲或检查网络连接');
      }
    } catch (e) {
      _playerState = MusicPlayerState.error;
      print('播放歌曲失败: $e');
    }
    
    notifyListeners();
  }

  /// 播放/暂停
  Future<void> togglePlayPause() async {
    if (_playerState == MusicPlayerState.playing) {
      await pause();
    } else if (_playerState == MusicPlayerState.paused) {
      await resume();
    } else if (_currentSong != null) {
      await playAtIndex(_currentIndex);
    }
  }

  /// 暂停
  Future<void> pause() async {
    await _audioPlayer.pause();
  }

  /// 继续播放
  Future<void> resume() async {
    await _audioPlayer.resume();
  }

  /// 停止
  Future<void> stop() async {
    await _audioPlayer.stop();
    _position = Duration.zero;
    _duration = Duration.zero;
    _playerState = MusicPlayerState.stopped;
    notifyListeners();
  }

  /// 下一首
  Future<void> next() async {
    int nextIndex = _getNextIndex();
    if (nextIndex != -1) {
      await playAtIndex(nextIndex);
    }
  }

  /// 上一首
  Future<void> previous() async {
    int prevIndex = _getPreviousIndex();
    if (prevIndex != -1) {
      await playAtIndex(prevIndex);
    }
  }

  /// 跳转到指定位置（带防抖机制）
  Future<void> seekTo(Duration position) async {
    // 取消之前的防抖定时器
    _seekDebounceTimer?.cancel();
    
    // 存储待处理的位置
    _pendingSeekPosition = position;
    
    // 设置防抖定时器，300ms后执行实际的seek操作
    _seekDebounceTimer = Timer(const Duration(milliseconds: 300), () async {
      await _performSeek(_pendingSeekPosition!);
    });
  }
  
  /// 立即跳转到指定位置（不使用防抖）
  Future<void> seekToImmediate(Duration position) async {
    _seekDebounceTimer?.cancel();
    await _performSeek(position);
  }
  
  /// 执行实际的seek操作
  Future<void> _performSeek(Duration position) async {
    if (_isSeeking) return; // 防止重复seek
    
    try {
      _isSeeking = true;
      
      // 确保位置在有效范围内
      final clampedPosition = Duration(
        milliseconds: position.inMilliseconds.clamp(0, _duration.inMilliseconds),
      );
      
      // 检查播放器状态
      if (_playerState == MusicPlayerState.error) {
        if (kDebugMode) {
          print('Player is in error state, skipping seek');
        }
        return;
      }
      
      await _audioPlayer.seek(clampedPosition);
      
      // 更新本地位置状态
      _position = clampedPosition;
      
      // 重置错误计数
      _seekErrorCount = 0;
      _lastError = null;
      
      // 如果之前是错误状态，尝试恢复
      if (_playerState == MusicPlayerState.error) {
        _playerState = MusicPlayerState.paused;
      }
      
      notifyListeners();
      
    } catch (e) {
      _seekErrorCount++;
      _lastError = e.toString();
      
      if (kDebugMode) {
        print('Seek error (attempt $_seekErrorCount/$_maxSeekErrors): $e');
      }
      
      // 如果错误次数超过限制，标记为错误状态
      if (_seekErrorCount >= _maxSeekErrors) {
        _playerState = MusicPlayerState.error;
        if (kDebugMode) {
          print('Too many seek errors, marking player as error state');
        }
      }
      
      notifyListeners();
    } finally {
      _isSeeking = false;
    }
  }
  
  /// 重置错误状态
  void clearError() {
    _lastError = null;
    _seekErrorCount = 0;
    if (_playerState == MusicPlayerState.error) {
      _playerState = MusicPlayerState.stopped;
    }
    notifyListeners();
  }

  /// 设置音量
  Future<void> setVolume(double volume) async {
    _volume = volume.clamp(0.0, 1.0);
    await _audioPlayer.setVolume(_volume);
    notifyListeners();
  }

  /// 设置播放模式
  void setPlayMode(PlayMode mode) {
    _playMode = mode;
    notifyListeners();
  }

  /// 歌曲播放完成时的处理
  void _onSongCompleted() {
    switch (_playMode) {
      case PlayMode.single:
        // 单曲循环，重新播放当前歌曲
        playAtIndex(_currentIndex);
        break;
      case PlayMode.sequence:
        // 顺序播放，播放下一首，如果是最后一首则停止
        if (hasNext) {
          next();
        } else {
          stop();
        }
        break;
      case PlayMode.loop:
        // 列表循环，播放下一首，如果是最后一首则播放第一首
        next();
        break;
      case PlayMode.shuffle:
        // 随机播放
        next();
        break;
    }
  }

  /// 获取下一首歌曲的索引
  int _getNextIndex() {
    if (_playlist.isEmpty) return -1;
    
    switch (_playMode) {
      case PlayMode.sequence:
        return _currentIndex + 1 < _playlist.length ? _currentIndex + 1 : -1;
      case PlayMode.loop:
        return (_currentIndex + 1) % _playlist.length;
      case PlayMode.single:
        return _currentIndex;
      case PlayMode.shuffle:
        if (_playlist.length <= 1) return _currentIndex;
        int nextIndex;
        do {
          nextIndex = (DateTime.now().millisecondsSinceEpoch % _playlist.length);
        } while (nextIndex == _currentIndex);
        return nextIndex;
    }
  }

  /// 获取上一首歌曲的索引
  int _getPreviousIndex() {
    if (_playlist.isEmpty) return -1;
    
    switch (_playMode) {
      case PlayMode.sequence:
        return _currentIndex - 1 >= 0 ? _currentIndex - 1 : -1;
      case PlayMode.loop:
        return _currentIndex - 1 >= 0 ? _currentIndex - 1 : _playlist.length - 1;
      case PlayMode.single:
        return _currentIndex;
      case PlayMode.shuffle:
        if (_playlist.length <= 1) return _currentIndex;
        int prevIndex;
        do {
          prevIndex = (DateTime.now().millisecondsSinceEpoch % _playlist.length);
        } while (prevIndex == _currentIndex);
        return prevIndex;
    }
  }

  @override
  void dispose() {
    _positionSubscription?.cancel();
    _durationSubscription?.cancel();
    _playerStateSubscription?.cancel();
    _seekDebounceTimer?.cancel(); // 清理防抖定时器
    _audioPlayer.dispose();
    _apiService.dispose();
    super.dispose();
  }
}
